package com.alibaba.csp.sentinel.dashboard.rule.nacos.gateway.api;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("gatewayApiRulePublish")
public class GatewayApiRulePublish implements DynamicRulePublisher<List<ApiDefinitionEntity>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(GatewayApiRulePublish.class);
    //底层借助 configService 与 Nacos 进行通信
    private final ConfigService configService;
    private final Converter<List<ApiDefinitionEntity>, String> converter;

    public GatewayApiRulePublish(ConfigService configService, Converter<List<ApiDefinitionEntity>, String> converter) {
        this.configService = configService;
        this.converter = converter;
    }

    /**
     * <h2>
     * Flow
     * </h2>
     *
     * @param app   app name
     * @param rules list of rules to push
     * @throws Exception
     */
    @Override
    public void publish(String app, List<ApiDefinitionEntity> rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        // 发布到 Nacos 的配置文件名是 ：
        // app + NacosConfigUtil.FLOW_DATA_ID_POSTFIX
        // 所属的 Nacos group 是 NacosConfigUtil.GROUP_ID 的值
        String convertedRule = converter.convert(rules);

        LOGGER.info("sentinel dashboard publisher api  rules : {}", convertedRule);
        configService.publishConfig(app + NacosConfigUtil.GATEWAY_API_DATA_ID_POSTFIX, NacosConfigUtil.GROUP_ID, convertedRule, ConfigType.JSON.getType());
    }
}
